package com.anbao.newanbao;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

import com.anbao.action.ActivityManagerAction;
import com.anbao.action.CmdMessageInfoAction;
import com.anbao.dataBean.MessageBaseBean;
import com.anbao.dataBean.UserBean;
import com.anbao.service.BaseMessgeService;
import com.anbao.service.MessService;
import com.anbao.util.CommonData;
import com.anbao.util.MessageCommonData;
import com.anbao.util.NumberUtil;
import com.anbao.util.SystemUtil;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;




/**
 * 登陆界面
 * @author tiansl
 *
 */
public class LoginActivity extends Activity {

	private BootstrapButton loginBtn;
	private  ProgressDialog pd;
	private  BootstrapEditText userName_text;
	private  BootstrapEditText pwd_text;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		//将当前界面加入到系统管理中国
		ActivityManagerAction.getScreenManager().pushActivity(this);
		iniView();
	}
	private void iniView() {
		
		userName_text = (BootstrapEditText) findViewById(R.id.userName_text);
		pwd_text = (BootstrapEditText) findViewById(R.id.pwd_text);
		
		loginBtn = (BootstrapButton) findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				login();
			}
		});
	}



	private String userNumber;
	private 		String pwd;
	private void login() {
		
		
		
		userNumber = 	userName_text.getText().toString();
		 pwd= 	pwd_text.getText().toString();
		
		 
		 
		 
		 
		 if(userNumber!=null&&!"".equals(userNumber)&&pwd!=null&&!"".equals(pwd)){
			 
			try {
				 long userid = Long.parseLong(userNumber);
			} catch (Exception e) {
				return ;
			}
		 }else{
			 return ;
			 
		 }
//		 
		 
		
		pd = ProgressDialog.show(LoginActivity.this, "", "登陆...");
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {

				LoginServiceImpl service = new LoginServiceImpl(LoginActivity.this);
				
				
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putInt("result", service.login(userNumber, pwd));
				msg.setData(data);
				handler.sendMessage(msg);
				
				
//				try {
//					Thread.sleep(2000);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//				
				
			
				
			}
		}).start();
		
	
	}
	
	
	private Handler handler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			//关闭进度条
			pd.cancel();
			
			Bundle data = 	msg.getData();
			
			int result =  data.getInt("result");
			
			if(result==0){
				Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				startActivity(intent);
				LoginActivity.this.finish();
			}else{
				Toast.makeText(LoginActivity.this, CmdMessageInfoAction.getErrorMsg(result), 1).show();
				
			}
			
		};
		
		
	};
	
	class LoginServiceImpl  extends BaseMessgeService implements MessService{
		
//		public static LoginService  loginService = null;
		
		/**
		 * -1表示服务器未返回数据，0登陆成功，其他表示错误码
		 */
		public  int  resultState = -1;

		
		private Context context;
		
		public LoginServiceImpl(Context context){
					this.context = context;
		}
		

		
		public int login(String userName,String pwd){
			
			UserBean usr = new UserBean();
			fillData(usr, pwd ,userName);
			byte[] data = getMessgeData(usr);
			//将状态值还原
			resultState = -1;
			 sendMessage(data);
			return resultState;
			
		}

		
		/**
		 * 发送数据
		 * @param data
		 * @return
		 */
		public  boolean sendMessage(byte[] data){
			
			//先将状态设置为初始化
				resultState=-1;
			//通过广播将登陆信息发送给socket服务
			   Intent mIntent = new Intent(CommonData.LOGINACTION);  
	           mIntent.putExtra("data", data);  
	           //发送广播  
	           this.context.sendBroadcast(mIntent); 
				for(int i =0 ; i < 3 ; i++){
					
					if(resultState!=-1){
						return true;
					}else{
						 try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
						
							e.printStackTrace();
						}
					}
				
			}
			
			
			return false;
			
			
			
		};
		
		
		//广播接收器
		  private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){  
		        @Override  
		        public void onReceive(Context context, Intent intent) {  
		            String action = intent.getAction();  
		            if(action.equals(CommonData.LOGINACTIONRESULT)){  
		            	
		            	
		            	
		            }  
		        }  
		          
		    };  
		      
		    /**
		     * 注册广播
		     */
		    public void registerBoradcastReceiver(){  
		        IntentFilter myIntentFilter = new IntentFilter();  
		        myIntentFilter.addAction(CommonData.LOGINACTIONRESULT);  
		        //注册广播        
		        context.registerReceiver(mBroadcastReceiver, myIntentFilter);  
		    }  
		
		/**
		 * 填充登陆对象
		 * @param usr
		 * @param pwd
		 * @param userName
		 */
		private void fillData(UserBean usr,String pwd,String userName) {

			usr.messageVersion = MessageCommonData.headCmd_commData.CMDVERSION;
			usr.messageType= MessageCommonData.headCmd_req.LOGIN_REQ;
			usr.usrType = MessageCommonData.usrType.MOBILE_USR;
			usr.messageNumber= 0;
			usr.usrid = Long.parseLong(userName);
			usr.pwd = NumberUtil.getMD5Byte(pwd);
			
		}
		/**
		 * 将对象转化为数组
		 * @param usr
		 * @return
		 */
		private byte[] getMessgeData(UserBean usr) {
			
		//获取头部数据
		List<Byte> list = 	getHeadList(usr);
		//填充密码数据
		for(int i =0 ; i < usr.pwd.length ; i ++){
			list.add(usr.pwd[i]);
		}
		
		//填充数据长度
		int size = list.size();
		list.add(0,(byte) ((size+2)/256));
		list.add(0,(byte) ((size+2)%256));
		
		size = list.size();
		
		byte[] data = new byte[size];
		
		
		for(int i=0 ; i <size;i++){
			data[i] = list.get(i);
			
		}
		
			return data;
		}
		
	
		

		public void setLoginResult(MessageBaseBean baseBean,List<Byte> data){
			
			 resultState = data.get(1)*256+data.get(0);
			
			if(resultState==0 && data.size()==39){
				//心跳周期
				SystemUtil.heartbeatTaskTime = data.get(2);
				
				byte[]  usrName_array = new byte[32];
				
				for(int i = 0 ; i < 32;i++){
					
					usrName_array[i] = data.get(i+3);
				}
				
				//登陆用户名
				SystemUtil.userName = new String(usrName_array);
					byte[] verificationCode_array = new byte[4];
				
					for(int i = 0 ; i < 4;i++){
						verificationCode_array[i] = data.get(35+i);
					}
					
					//登陆验证码
					SystemUtil.verificationCode = NumberUtil.byteArrayToInt(verificationCode_array);					
				
				
			}
			
			
		}

		@Override
		public void regMessageResult() {
			
		}
		
	}

}
